package com.hg.library.widget;

import java.util.ArrayList;
import java.util.List;

/**
 * 循环链表
 */
public class LoopLinkList<T> {

    private List<T> tList = new ArrayList<>();

    private int position;

    public void add(T object) {
        tList.add(object);
    }

    public void addAll(List<T> ts) {
        tList.addAll(ts);
    }

    public void remove(int index) {
        tList.remove(index);
    }

    public void remove(T object) {
        tList.remove(object);
    }

    public T get(int location) {
        return tList.get(location);
    }

    public T get() {
        return tList.get(position);
    }

    public LoopLinkList(){}

    public LoopLinkList(int size){
        tList = new ArrayList<>(size);
    }

    public synchronized T leftNext() {
        int index = tList.size() - 1;
        position = --position;
        if (position < 0) position = index;
        return get(position);
    }

    public synchronized T rightNext() {
        int index = tList.size() - 1;
        position = ++position;
        if (position > index) position = 0;
        return get(position);
    }

    @Deprecated
    public int getLoacaIndex(){
        return position;
    }

    @Deprecated
    public void setLoacaIndex(int localIndex){
        position = localIndex;
    }

    public int getLocalIndex(){
        return position;
    }

    public void setLocalIndex(int localIndex){
        position = localIndex;
    }

    public synchronized T leftNext(int localIndex) {
        leftNext();//position - 1
        if (position - (localIndex -1) < 0){
            int i = position - (localIndex -1);
            return tList.get(tList.size() + i);
        }
        return tList.get(position - (localIndex -1));
    }

    public synchronized int leftNextIndex(int localIndex){
        if (position - localIndex < 0){
            int i = position - localIndex;
            return i + tList.size();
        }
        return position - localIndex;
    }

    public synchronized T rightNext(int localIndex) {
        rightNext();//position + 1
        if (position + (localIndex -1) > tList.size() - 1){
            int i = position + (localIndex -1);
            return tList.get(i - tList.size());
        }
        return tList.get(position + (localIndex -1));
    }

    public synchronized int rightNextIndex(int localIndex){
        if (position + localIndex > tList.size() - 1){
            int i = position + localIndex;
            return i - tList.size();
        }
        return position + localIndex;
    }

    public synchronized void set(int position,T t){
        tList.set(position,t);
    }

    public void clear(){
        tList.clear();
    }

    public int size(){
        return tList.size();
    }
}
